package priv.xakml.demo.mysql.service.impl;

import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import priv.xakml.demo.mysql.Person;
import priv.xakml.demo.mysql.PersonMapper;
import priv.xakml.demo.mysql.service.IPersonService;

import javax.annotation.Resource;
import javax.swing.*;
import java.util.List;

/**
 * @author lhx
 * @date 2021-09-07 18:02
 **/
@Service
public class PersonService implements IPersonService {

    private final PersonMapper personMapper;

    @Resource
    private SqlSessionFactory sqlSessionFactory;

    @Autowired
    public PersonService(PersonMapper personMapper) {
        this.personMapper = personMapper;
    }

    public List<Person> getAll(){
        return this.personMapper.getAll();
    }
    public int insert(Person person){
//        try {
            return personMapper.insertPerson(person);
//        }catch (org.springframework.dao.DuplicateKeyException ex){
//            System.out.println("congfu");
//            System.out.println(ex.getMessage());
//            System.out.println(ex.getCause().getMessage());
////            ex.printStackTrace();
//        }
//        return  0;
    }

    public boolean insertBatch(List<Person> list){
        //Object rtnValue = this.personMapper.insertPersonBatch(list);
        long rowAffect = this.personMapper.insertPersonBatch(list);
        return rowAffect > 0;
    }

    /**
     * 手动批量插入
     * @param list
     * @return
     */
    public boolean insertBatchManual(List<Person> list){
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH,false);
        PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
        long rowAffect = mapper.insertPersonBatch(list);
        sqlSession.commit();
        sqlSession.clearCache();
        return  rowAffect > 0;
    }

    public  Person getPersonById(int pid) {
        Person person = this.personMapper.getPersonById(pid);
        return person;
    }
}
